package com.demo.virtual_thread;

import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class VirtualThreadsExample {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 演示使用虚线程执行任务
        System.out.println("=== 使用虚线程执行任务 ===");
        runWithVirtualThreads();
        
        // 演示使用平台线程执行相同任务作为对比
        System.out.println("\n=== 使用平台线程执行任务 ===");
        runWithPlatformThreads();
    }
    
    /**
     * 使用虚线程执行任务
     */
    private static void runWithVirtualThreads() throws InterruptedException, ExecutionException {
        Instant start = Instant.now();
        
        // 创建一个可以创建虚线程的ExecutorService
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            List<Future<?>> futures = new ArrayList<>();
            
            // 提交1000个任务到 executor
            for (int i = 0; i < 1000; i++) {
                final int taskNumber = i;
                futures.add(executor.submit(() -> {
                    performTask(taskNumber);
                    return null;
                }));
            }
            
            // 等待所有任务完成
            for (Future<?> future : futures) {
                future.get();
            }
        }
        
        Instant end = Instant.now();
        System.out.printf("所有虚线程任务完成，耗时: %d 毫秒%n", 
            Duration.between(start, end).toMillis());
    }
    
    /**
     * 使用平台线程执行任务（作为对比）
     */
    private static void runWithPlatformThreads() throws InterruptedException, ExecutionException {
        Instant start = Instant.now();
        
        // 创建一个使用平台线程的ExecutorService
        try (ExecutorService executor = Executors.newFixedThreadPool(100)) {
            List<Future<?>> futures = new ArrayList<>();
            
            // 提交1000个任务到 executor
            for (int i = 0; i < 1000; i++) {
                final int taskNumber = i;
                futures.add(executor.submit(() -> {
                    performTask(taskNumber);
                    return null;
                }));
            }
            
            // 等待所有任务完成
            for (Future<?> future : futures) {
                future.get();
            }
        }
        
        Instant end = Instant.now();
        System.out.printf("所有平台线程任务完成，耗时: %d 毫秒%n", 
            Duration.between(start, end).toMillis());
    }
    
    /**
     * 执行具体任务
     */
    private static void performTask(int taskNumber) {
        try {
            // 模拟任务执行时间
            Thread.sleep(Duration.ofMillis(100));
            
            // 打印当前线程信息
            Thread currentThread = Thread.currentThread();
            System.out.printf("任务 %d 完成，线程: %s (类型: %s)%n",
                    taskNumber,
                    currentThread.getName(),
                    currentThread.isVirtual() ? "虚线程" : "平台线程");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.out.printf("任务 %d 被中断%n", taskNumber);
        }
    }
}
